// pages/sousuo/sousuo.js
import { request } from "../../pages/request2/request2";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    searchValue:"",
    searchRecord: [],
    goods:[],
    blo:false,
    solist:[]
  },
  so(){

  },
  openHistorySearch: function() {
    this.setData({
      searchRecord: wx.getStorageSync('searchRecord') || [] //若无存储则为空
    })
  },
  quxiao(){
    this.data.goods=[]
    this.setData({
      goods:[],
      searchValue:''
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
  
    this.openHistorySearch()
   
  },
  val(e){
    console.log(e);
    this.setData({
      searchValue:e.target.id
    })
  },
  btn(e){
    console.log(e);
  },
  rem(e){
    console.log(e);
    
    let id = e.target.id
    var searchRecord = this.data.searchRecord
    let sear = wx.get
    searchRecord.map((item,index)=>{
      console.log(id,index);
      if(id==index){
        searchRecord.splice(index,1)
      }
    })
    this.setData({
      searchRecord
    })
    wx.setStorageSync('searchRecord', searchRecord)
  },
  searchSubmitFn: async function (e) {
    var that = this
    var inputVal = e.detail.value.input
    var searchRecord = this.data.searchRecord
    if (inputVal == '') {
      //输入为空时的处理
      this.setData({
        goods:[]
      })
    }
    else {
      //将搜索值放入历史记录中,只能放前五条
      if (searchRecord.length < 5) {
        searchRecord.unshift(
          {
            value: inputVal,
            id: searchRecord.length
          }
        )
      }
      else {
        searchRecord.pop()//删掉旧的时间最早的第一条
        searchRecord.unshift(
          {
            value: inputVal,
            id: searchRecord.length
          }
        )
      }
    //将历史记录数组整体储存到缓存中
    this.setData({
      searchValue:e.detail.value.input
    })
    const res = await request({
      url: `/goods/qsearch`,
      data:{query:this.data.searchValue}
    })
    this.setData({
      goods:res
    })
    this.setData({
      searchRecord
    })
    wx.setStorageSync('searchRecord', searchRecord)
    }
    this.setData({
      searchValue:""
    })
  },
  historyDelFn: function () {
    wx.clearStorageSync('searhRecord')
    this.setData({
      searchRecord: [],
      goods:[],
      searchValue:""
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let solist = wx.getStorageSync('sosuo')
    this.setData({
      solist
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})